<template>
	<view class="page">
		<u-navbar title="通过语音" back-icon-color="#fff" title-color="#fff" :background="background"></u-navbar>
		<view class="options flex-row justify-around mt-30">
			<view class="flex-col flex-1 items-center" @click="checkClick(index)" v-for="(item,index) in optionList" :key="index">
				<image :src="item.img" mode="" class="opt-img"></image>
				<text class="opt-text">{{item.name}}</text>
			</view>
		</view>
		<view class="desc flex-row justify-center mt-60">
			<image class="desc-img" src="https://terminator.axu9.com/images/edit-desc.png" mode=""></image>
		</view>
		
		<!-- 添加音色标题弹窗 -->
		<audioTitlePop ref="audiotitle" @submit="submit" :isLoading="isLoading"></audioTitlePop>
		
		<!-- 上传视频进度条弹窗 -->
		<progressPop ref="progressPop" :isShow="true" :percent="percent" @cancel="showProgressCancel"></progressPop>
		
	</view>
</template>

<script>
	import audioTitlePop from "../../components/audioTitlePop/index.vue";
	import progressPop from "../../components/progressPop/index.vue";
	import {
		myYinseFileup,
		myYinseFileupNew,
		morenShengYin,
		MinorlanguagesTiqu//提取音色
	} from "@/api/audio.js"
	import { getQiniuToken } from "@/api/user.js"
	import {
		completQiniuUploadUrl,
		qiniuDomainUrlD,
		baseURL1
	} from "@/api/request.js"
	import { yinseTiqu, getYinseTiqu } from "@/api/video.js"
	export default {
		components: {
			audioTitlePop,
			progressPop
		},
		data() {
			return {
				background: {
					backgroundColor: 'rgba(0,0,0,0)',
				},
				optionList: [{
						img: 'https://terminator.axu9.com/images/luyin-edit.png',
						name: '记录'
					},
					{
						img: 'https://terminator.axu9.com/images/shipin-edit.png',
						name: '视频声音'
					},
					{
						img: 'https://terminator.axu9.com/images/bendi-edit.png',
						name: '文件夹声音'
					}
				],
				timbreId: '',
				audioUrl: '',
				isLoading: false, //是否加载中
				editTribreErrNum: 0,//修改音色第二部失败次数
				percent: 0, //进度条
				uploadTask: null, //上传视频任务
				isxiao:false,
				list_id:"",
				timer: null,//查看视频提取音频状态 定时器
			}
		},
		onLoad(options) {
			console.log(options, 'options')
			this.timbreId = options.id;
			if(options.type == "editxiao"){
				this.isxiao = true
				this.list_id = options.listid
			}
		},
		methods: {
			// 上传视频
			chooseVideo() {
				var _this = this;
				uni.chooseMedia({
					count: 1,
					mediaType: ['video'],
					sourceType: ['album'],
					sizeType: ['compressed','original'],
					success: (res) => {
						console.log(res, 'dddddd')
						_this.$refs.progressPop.open();
						// 在这里处理压缩后的视频路径 compressRes.tempFilePath
						_this.uploadQiniuReauest(res.tempFiles[0].tempFilePath, res
							.tempFiles[0]
							.thumbTempFilePath)
					},
					fail: (err) => {
						console.log('选择视频失败：', err);
					}
				})
			},
			// 七牛上传接口封装
			uploadQiniuReauest(videoUrl, imgUrl) {
				// uni.showLoading({
				// 	title: '上传中'
				// })
			
				var timestamp = Date.now();
				var userId = uni.getStorageSync('userId');
				var name = userId + '/' + this.generateRandomString(8) + timestamp;
			
				var _this = this;
				getQiniuToken().then(res => {
					let token = res.data;
					console.log(res.data, '获取七牛token')
					_this.uploadTask = uni.uploadFile({
						filePath: videoUrl,
						name: 'file',
						url: completQiniuUploadUrl,
						timeout: 1000000,
						formData: {
							token: token,
							key: name
						},
						success: (uploadFileRes) => {
							uni.hideLoading()
							let logo = JSON.parse(uploadFileRes.data);
							console.log(logo, 'logo')
							if (logo.key) {
								console.log(qiniuDomainUrlD + logo.key, '上传路径');
								_this.videoPath = qiniuDomainUrlD + logo.key
								_this.videoYinseTiqu(_this.videoPath)
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'error'
								})
								_this.$refs.progressPop.close();
							}
			
						},
						fail: (err) => {
							uni.hideLoading()
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
							// reject(err)
						}
					})
					// 监听上传进度  
					_this.uploadTask.onProgressUpdate((res) => {
						// this.uploadPercent = res.progress; // 更新进度条  
						// console.log('上传进度', res.progress);
						this.percent = res.progress;
						if (this.percent >= 100) {
							this.$refs.progressPop.close();
							setTimeout(() => {
								this.percent = 0;
							}, 1000)
			
						}
					});
				})
			
			
			},
			// 随机获取字符串
			generateRandomString(length) {
				const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
				let result = '';
				const charactersLength = characters.length;
				for (let i = 0; i < length; i++) {
					result += characters.charAt(Math.floor(Math.random() * charactersLength));
				}
				return result;
			},
			// 关闭上传进度弹窗
			showProgressCancel() {
				console.log('关闭上传弹窗')
				this.uploadTask.abort();
				this.uploadTask = null;
			},
			// 视频提取音色
			videoYinseTiqu(url){
				uni.showLoading({
					title: '提取中'
				})
				yinseTiqu({
					uid: uni.getStorageSync("userId"),
					video_url: url
				}).then(res => {
					if(res.errno == 0){
						console.log(res.data,'视频提取音色')
						
						this.getCreateStatus(res.data)
						this.timer = setInterval(() => {
							this.getCreateStatus(res.data);
						}, 1000)
						
					}else {
						uni.hideLoading();
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 1000
						})
					}
				}).catch(err=> {
					uni.hideLoading();
					uni.showToast({
						title: '出错了',
						icon: 'none',
						duration: 1000
					})
				})
			},
			// 查询视频生成状态
			getCreateStatus(id){
				var _this = this;
				getYinseTiqu({
					id: id
				}).then(res => {
					if(res.errno == 0){
						var status = res.data.status;
						if(status == 0){
							console.log('生成中')
						}else if (status == 1) {
							// 成功
							clearInterval(this.timer)
							uni.hideLoading();
							_this.audioUrl = res.data.mp3;
							if(_this.isxiao){
								_this.getTiqu(_this.audioUrl)
								return
							}
							_this.$refs.audiotitle.open();
						
						} else if (status == 2) {
							// 失败
							clearInterval(this.timer)
							uni.hideLoading();
							uni.showToast({
								title: '提取失败',
								icon: 'none',
								duration: 1000
							})
						}
					}
				})
			},
			// editTimbreUpload(){
			// 	myYinseFileup({
			// 		//// uid: uni.getStorageSync("userId"),
			// 		id: this.timbreId,
			// 		title: this.audioTitle,
			// 		mp3: this.audioUrl
			// 	}).then(res => {
			// 		console.log(res, 'ressss')
					
			// 		if (res.errno == 0) {
			// 			console.log(this.videoPath, 'this.videoPath')
			// 			this.$refs.audiotitle.close();
			// 			// this.getTimbreList();
			// 			uni.showToast({
			// 				title: '成功',
			// 				icon: 'none',
			// 				durat: 1000
			// 			})
			// 			setTimeout(()=>{
			// 				this.isLoading = false;
			// 				uni.hideLoading();
			// 				uni.reLaunch({
			// 					url: '/pages/mine/index?current=1'
			// 				})
			// 			},1500)
			// 		} else {
			// 			uni.showToast({
			// 				title: res.msg,
			// 				icon: 'none',
			// 				durat: 1000
			// 			})
			// 			this.$refs.audiotitle.close();
			// 			setTimeout(()=>{
			// 				this.isLoading = false;
			// 				uni.hideLoading();
			// 				uni.reLaunch({
			// 					url: '/pages/mine/index?current=1'
			// 				})
			// 			},1500)
						
						
			// 		}
			// 	}).catch(err => {
					
			// 		console.log(err, 'err')
			// 		uni.showToast({
			// 			title: '出错了,请重新上传',
			// 			icon: 'none',
			// 			duration: 1000
			// 		})
			// 		this.$refs.audiotitle.close();
			// 		setTimeout(()=>{
			// 			this.isLoading = false;
			// 			uni.hideLoading();
			// 			uni.reLaunch({
			// 				url: '/pages/mine/index?current=1'
			// 			})
			// 		},1500)
			// 	})
							
			// },
			editTimbreUploadSecond(id,uid,voice_name,title,mp3){
				uni.hideLoading();
				uni.showLoading({
					title: '语音生成中'
				})
				// var _this = this;
				morenShengYin({
					id: id,
					voice_name: voice_name,
					uid: uid,
					title: title,
					mp3: mp3
				}).then(res => {
					console.log(res, 'ressss')
					
					if (res.errno == 0) {
						uni.showToast({
							title: '成功',
							icon: 'none',
							durat: 1000
						})
						this.$refs.audiotitle.close();
						setTimeout(()=>{
							this.isLoading = false;
							uni.hideLoading();
							uni.reLaunch({
								url: '/pages/mine/index?current=1'
							})
						},1500)
					} else {
						uni.hideLoading()
						this.editTribreErrNum++;
						if(this.editTribreErrNum <5){
							uni.showLoading({
								title: '语音生成中'
							})
							setTimeout(()=>{
								this.editTimbreUploadSecond(id,uid,voice_name,title,mp3)
							},1000)
							
						}else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								durat: 1000
							})
							this.$refs.audiotitle.close();
							setTimeout(()=>{
								this.isLoading = false;
								uni.hideLoading();
								uni.reLaunch({
									url: '/pages/mine/index?current=1'
								})
							},1500)
						}
					}
				}).catch(err => {
					
					uni.showToast({
						title: res.msg,
						icon: 'none',
						durat: 1000
					})
					this.$refs.audiotitle.close();
					setTimeout(()=>{
						this.isLoading = false;
						uni.hideLoading();
						uni.reLaunch({
							url: '/pages/mine/index?current=1'
						})
					},1500)
				})
			},
			editTimbreUpload(){
				myYinseFileupNew({
					//// uid: uni.getStorageSync("userId"),
					id: this.timbreId,
					title: this.audioTitle,
					mp3: this.audioUrl
				}).then(res => {
					console.log(res, 'ressss')
					
					if (res.errno == 0) {
						
						console.log(this.videoPath, 'this.videoPath')
						var data = res.data;
						setTimeout(()=>{
							this.editTimbreUploadSecond(data.id,data.uid,data.voice_name,data.title,data.mp3)
						},1000)
						
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							durat: 1000
						})
						this.$refs.audiotitle.close();
						setTimeout(()=>{
							this.isLoading = false;
							uni.hideLoading();
							uni.reLaunch({
								url: '/pages/mine/index?current=1'
							})
						},1500)
						
						
					}
				}).catch(err => {
					
					console.log(err, 'err')
					uni.showToast({
						title: '出错了,请重新上传',
						icon: 'none',
						duration: 1000
					})
					this.$refs.audiotitle.close();
					setTimeout(()=>{
						this.isLoading = false;
						uni.hideLoading();
						uni.reLaunch({
							url: '/pages/mine/index?current=1'
						})
					},1500)
				})
							
			},
			// 输入标题--确定
			submit(data) {
				console.log(data, 'submit')
				this.audioTitle = data
				if(this.isLoading == true){
					return
				}
				uni.showLoading({
					title: '上传中'
				})
				this.isLoading = true;
				console.log('走了么')
				// return
				this.editTimbreUpload()
				
			},
			uploadAudio(filePath, fileName) {
				var _this = this;
				_this.$upload(filePath).then(res => {
					console.log(res, 'uploadImg')
					if (res.data.errno == 1) {
						_this.audioUrl = res.data.img
						// _this.audioName = fileName
						console.log(_this.audioUrl, '上传音频')
						
						if(this.isxiao){
							this.getTiqu( res.data.img)
							return
						}
						
						_this.$refs.audiotitle.open();
					} else {
						uni.showToast({
							title: res.data.message,
							icon: 'none'
						})
					}
			
			
				}).catch(err => {
					console.log(err, 'err')
					uni.showToast({
						title: '出错了',
						icon: 'none'
					})
			
				})
			},
			checkClick(index){
				if(index == 0){
					uni.navigateTo({
						url: '/pagesCreate/addAudio/index?toAddType=1' + '&timbreId=' + this.timbreId + '&isxiao='+this.isxiao + "&listid="+ this.list_id
					})
					// uni.navigateTo({
					// 	url: '/pagesCreate/addAudio/index?toAddType=1' + '&timbreId=' + this.timbreId
					// })
				}else if(index == 1){
					// uni.showToast({
					// 	title: '开发中',
					// 	icon: 'none'
					// })
					// 视频提取音频
					this.chooseVideo()
				}else if(index == 2){
					// #ifdef MP
					var _this = this;
					wx.chooseMessageFile({
						count: 1, // 默认99
						type: 'file', // 选择文件的类型
						extension: ['mp3', 'm4a', 'amr', 'wav', 'aac','MP3','M4A','AMR','WAV','AAC'], // 选择文件的扩展名
						// extension: ['.m﻿4a', '.mp3'],
						success: function(res) {
							const filePath = res.tempFiles[0].path; // 获取音频文件的临时路径
							// const fileName = res.tempFiles[0].name;
							console.log(res, 'res')
							_this.uploadAudio(filePath);
					
						}
					});
					// #endif
				}
			},
			// 提取音色
			getTiqu(url){
				uni.showLoading({
					title: '提取中',
					mask:true
				})
				console.log(url,"提取音色");
				MinorlanguagesTiqu({
					uid: uni.getStorageSync('userId'),
					voiceUrl:url,
					lan_id:this.timbreId,
					list_id:this.list_id
				}).then(res=>{
					uni.hideLoading()
					if(res.errno == 0){
						uni.showToast({
							title:"提取成功",
							icon:"none"
						})
						setTimeout(()=>{
							uni.navigateBack({
								delta:1,
							})
						},1000)
						console.log(res,"提取音色");
					}else {
						uni.showToast({
							title:res.msg,
							icon:"none"
						})
					}
					
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: '提取失败',
						icon: 'none'
					})
				})
				
			}
		}
	}
</script>
<style lang="less" scoped>
	/deep/ .u-drawer-bottom {
		background-color: rgba(0, 0, 0, 0) !important;
	}

	/deep/ .u-mode-center-box {
		background-color: rgba(0, 0, 0, 0) !important;
	}
</style>

<style>
	@import url(../../static/css/common.css);

	page {
		padding-bottom: 61rpx;
		background-color: #111113;
		height: 100%;
		width: 100%;
		overflow-y: auto;
		overflow-x: hidden;
	}
	.mt-30 {
		margin-top: 30rpx;
	}
	.mt-60 {
		margin-top: 60rpx;
	}

	.page {
		width: 100%;
		background-image: url("https://terminator.axu9.com/images/edit-temb-bg.png");
		background-repeat: no-repeat;
		background-size: 100% 494rpx;
	}

	.desc-img {
		width: 672rpx;
		height: 1117rpx;
	}

	.opt-img {
		width: 142rpx;
		height: 141rpx;
		margin-bottom: 30rpx;
	}

	.opt-text {
		font-size: 28rpx;
		font-family: PingFang SC;
		line-height: 26rpx;
		color: #ffffff;
	}
</style>